import 'dart:async';

///future是一个异步任务的封装
///他提供了让自己进行任务转换的过程
///Future() - 默认为timer
///Future.sync() - 同步在主线执行
///Future.microtask() - 转换微任务
///Future.value(val) 根据值选择
///       val = 常量  -->microtask
///       val = 异步  --->按照对应异步方案处理
void main() {
  test1();//默认为timer
  test2();//Future.microtask() - 转换微任务
  test3();//Future.microtask() - 转换微任务
  // test4();//根据值选择
}

/// Future() - 默认为timer
void test1(){
  print("main begin ...");

  scheduleMicrotask(() {
    print("ScheduleMicrotask - A - in Timer A");
    //依托的是事件队列
    Future f = Future(() {
      print("future create ...");
      return 123;
    }).then((value) {
      print("future then1 value:$value...");
      return 567;
    }).then((value) {
      print("future then2 value:$value...");
    });
    f.onError((error, stackTrace) => print("出现异常"));
    f.whenComplete(() => "ok");
  });

  print("main end ...");
  Timer.run(() {
    print("timer - event - A");

    scheduleMicrotask(() {
      print("ScheduleMicrotask - A - in Timer A");
    });

    scheduleMicrotask(() {
      print("ScheduleMicrotask - B - in Timer A");
    });
  });
}

///Future.microtask() - 转换微任务
void test2(){
  print("main begin ...");

  scheduleMicrotask(() {
    print("ScheduleMicrotask - A - in Timer A");
    Future f = Future.microtask(() {
      print("future create ...");
      return 123;
    }).then((value) {
      print("future then1 value:$value...");
      return 567;
    }).then((value) {
      print("future then2 value:$value...");
    });
    f.onError((error, stackTrace) => print("出现异常"));
    f.whenComplete(() => "ok");
  });

  print("main end ...");
  Timer.run(() {
    print("timer - event - A");

    scheduleMicrotask(() {
      print("ScheduleMicrotask - A - in Timer A");
    });

    scheduleMicrotask(() {
      print("ScheduleMicrotask - B - in Timer A");
    });
  });
}


///Future.sync() - 同步执行
void test3(){
  print("main begin ...");
  Future f = Future.sync(() {
    print("future create ...");
    return 123;
  }).then((value) => print("future then 1"));

  scheduleMicrotask(() {
    print("ScheduleMicrotask - A - in Timer A");

  });

  print("main end ...");
  Timer.run(() {
    print("timer - event - A");

    scheduleMicrotask(() {
      print("ScheduleMicrotask - A - in Timer A");
    });

    scheduleMicrotask(() {
      print("ScheduleMicrotask - B - in Timer A");
    });
  });
}



///Future.value() - 同步执行
void test4(){
  print("main begin ...");
  // Future f = Future.value(123).then((value) => print("future then 1"));
  Future f = Future.value(Future((){
    print("Future.value(Future(()) ");
  })).then((value) => print("future then 1"));
  scheduleMicrotask(() {
    print("ScheduleMicrotask - A - in Timer A");

  });

  print("main end ...");
  Timer.run(() {
    print("timer - event - A");

    scheduleMicrotask(() {
      print("ScheduleMicrotask - A - in Timer A");
    });

    scheduleMicrotask(() {
      print("ScheduleMicrotask - B - in Timer A");
    });
  });
}